using System;
using System.Collections.Generic;
using System.Text;
using Ltf.Remoting.TeamFoundation;
using Microsoft.TeamFoundation.VersionControl.Client;
using System.IO;
using Ltf.Remoting.Operations;

namespace Ltf.Diffs.MergeCommands
{
	public class MergeException : Exception
	{
		public MergeException(string message)
			: base(message)
		{ }
	}

	public class MergeResult
	{
		public int MergedFiles = 0;
		public int RenamedFiles = 0;
		public int MovedFiles = 0;
		public int NewFiles = 0;
		public int DeletedFiles = 0;
		public int UnDeletedFiles = 0;

		public MergeResult()
		{ }

		public MergeResult(int mergedFiles, int renamedFiles, int movedFiles, int newFiles, int deletedFiles, int unDeletedFiles)
		{
			MergedFiles = mergedFiles;
			RenamedFiles = renamedFiles;
			MovedFiles = movedFiles;
			NewFiles = newFiles;
			DeletedFiles = deletedFiles;
			UnDeletedFiles = unDeletedFiles;
		}

		public static MergeResult operator +(MergeResult x, MergeResult y)
		{
			MergeResult result = new MergeResult();
			result.MergedFiles = x.MergedFiles + y.MergedFiles;
			result.RenamedFiles = x.RenamedFiles + y.RenamedFiles;
			result.MovedFiles = x.MovedFiles + y.MovedFiles;
			result.NewFiles = x.NewFiles + y.NewFiles;
			result.DeletedFiles = x.DeletedFiles + y.DeletedFiles;
			result.UnDeletedFiles = x.UnDeletedFiles + y.UnDeletedFiles;

			return result;
		}
	}

	public abstract class MergeCommand
	{

		private TFServerConnection connection;

		public TFServerConnection Connection
		{
			get { return connection; }
			set { connection = value; }
		}

		public Workspace GetWorkSpaceForTargetPath()
		{
			if (connection == null)
				return null;

			Workspace ws = connection.GetWorkspace(Path.GetDirectoryName(TargetFile));
			return ws;
		}

		public WorkspaceOperators GetWorkspaceOperators()
		{
			if (Connection == null)
				return null;

			Workspace ws = GetWorkSpaceForTargetPath();

			if (ws == null)
				return null;

			return new WorkspaceOperators(Connection, ws);
		}

		private string targetFile;

		public string TargetFile
		{
			get { return targetFile; }
			set { targetFile = value; }
		}

		protected void BackupTargetFile()
		{
			int i = 0;
			string copyFileName;
			while (File.Exists(copyFileName = string.Format("{0}.{1}", TargetFile, i)))
				i++;
			File.Copy(TargetFile, copyFileName);
		}

		public abstract MergeResult Execute();

		public abstract void Validate();

		public abstract string  ShortName
		{ get; }
	}
}
